package com.meihua.baoleyi.fragment.order;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.meihua.baoleyi.R;
import com.meihua.baoleyi.adapters.OrderRVAdapter;
import com.meihua.baoleyi.base.BaseRecyclerViewBannerFragment;
import com.meihua.baoleyi.bean.MyOrderBean;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.ui.CommonWebActivity;
import com.meihua.baoleyi.view.IRecyclerView;
import com.meihua.baoleyi.view.LoadMoreFooterView;

import java.util.ArrayList;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liming on 2017/10/17
 * 全部
 */

public class OrderFragment extends BaseRecyclerViewBannerFragment implements OrderRVAdapter.OnItemClickListener {

    private static final String ACTION_NAME = "OrderFragment";
    @Bind(R.id.iRecyclerView)
    IRecyclerView iRecyclerView;
    private String url;
    private ArrayList<MyOrderBean.DataBean> mData;
    private OrderRVAdapter rvAdapter;
    private View view;
    private int type;

    private final int limit = 10; //每页记录数
    private MyBroadcastReceiver mBroadcastReceiver;

    /**
     * 视图是否已经初初始化
     */
    protected boolean isInit = false;
    protected boolean isLoad = false;

    /*实例化*/
    public static OrderFragment newInstance(String url, int i) {
        OrderFragment mInstance = new OrderFragment();
        Bundle args = new Bundle();
        args.putString("url", url);
        args.putInt("type", i);//各个页面的标识
        mInstance.setArguments(args);
        return mInstance;
    }

    /**
     * initview
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view==null) {
            view = inflater.inflate(R.layout.fragment_order_list, container, false);
        }
        if (null != getArguments()) {
            url = getArguments().getString("url");
            type = getArguments().getInt("type");
        }
        //注册广播
        registerBroadcastReceiver();
        ButterKnife.bind(this, view);

        isInit = true;
        /**初始化的时候去加载数据**/
        isCanLoadData();
        return view;
    }

    /**
     * 视图是否已经对用户可见，系统的方法
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isInit) {
            return;
        }

        if (getUserVisibleHint() && !isLoad) {
            lazyLoad();
            isLoad = true;
        } else {
            if (isLoad) {
                stopLoad();
            }
        }
    }

    private void stopLoad() {

    }

    private void lazyLoad() {
        isok = true;
        initRecyclerView(iRecyclerView, new LinearLayoutManager(getActivity()), false, false);
    }

    private boolean isok;

    /**
     * 获取adapter
     * @return
     */
    @Override
    protected RecyclerView.Adapter getAdapter() {
        mData = new ArrayList<>();
        rvAdapter = new OrderRVAdapter(mData,type,this);
        rvAdapter.setOnItemClickListener(this);
        return rvAdapter;
    }

    /**
     * 获取服务器数据
     * @param page
     */
    @Override
    public void getServiceData(final int page) {
        TreeMap<String, String> treeMap = new TreeMap<String, String>() {
            {
                put("user_id", MyApp.getInstance().getUser_id());
                put("page", page + "");
                put("limit", limit + "");
            }
        };
        NetHelper.post(url, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                MyOrderBean bean = NetHelper.getBeanForJson(MyOrderBean.class, s);
                if (bean == null) return;
                if (null != bean.getData()) {
                    if (bean.getData().size() != 0) {
                        if (page == 1) {
                            /*刷新*/
                            if(null!=iRecyclerView)iRecyclerView.setRefreshing(false);
                            mData.clear();
                        }
                        mData.addAll(bean.getData());
                        rvAdapter.notifyDataSetChanged();
                    } else {
                        if (iRecyclerView != null) {
                            iRecyclerView.setRefreshing(false);
                        }
                        if (page == 1) {
                            if (null != iRecyclerView) iRecyclerView.setRefreshing(false);
                            mData.clear();
                            rvAdapter.notifyDataSetChanged();
                        }
                        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
                    }
                } else {
                    mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;
        ButterKnife.unbind(this);
    }

    @Override
    public void onItemClick(MyOrderBean.DataBean bean) {
        /*点击进入H5界面*/
        Intent intent = new Intent(getActivity(),CommonWebActivity.class);
        intent.putExtra("url", APIServer.ORDERDETAILS+MyApp.getInstance().getUser_id()+"/"+bean.getOrder_id()+"/"+MyApp.getInstance().getToken());
        startActivity(intent);
    }

    /**
     * 定义一个广播
     */
    public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (isok) {
                getServiceData(1);
            }
        }
    }

    ;

    /**
     * 注册广播
     */
    private void registerBroadcastReceiver() {
        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ACTION_NAME);
        getContext().registerReceiver(mBroadcastReceiver, mFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解注册
        getContext().unregisterReceiver(mBroadcastReceiver);
    }

}
